package com.clb.toolsbox.toolsJPanel;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class TimestampConvertTool extends JPanel {
    private JTextField timestampField;
    private JTextField datetimeField;
    private JButton toDatetimeButton;
    private JButton toTimestampButton;
    private JLabel resultLabel;
    private JButton copyButton;

    private String lastResult = ""; // 保存最后一次结果用于复制

    // 新增：当前时间与时间戳相关组件
    private JLabel currentDateTimeLabel;
    private JLabel currentTimestampLabel;
    private JButton copyDateTimeButton;
    private JButton copyTimestampButton;

    public TimestampConvertTool() {
        initializeUI();
        updateCurrentTime(); // 初始化当前时间
        startAutoUpdateTime(); // 启动定时更新
    }

    private void initializeUI() {
        setLayout(new BorderLayout(10, 10));

        // ===== 当前时间展示区域（新增）=====
        JPanel timeInfoPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;

        currentDateTimeLabel = new JLabel("当前时间：加载中...");
        currentTimestampLabel = new JLabel("当前时间戳：加载中...");

        copyDateTimeButton = new JButton("复制");
        copyTimestampButton = new JButton("复制");

        copyDateTimeButton.addActionListener(e -> copyText(currentDateTimeLabel.getText().replace("当前时间：", "")));
        copyTimestampButton.addActionListener(e -> copyText(currentTimestampLabel.getText().replace("当前时间戳：", "")));

        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        timeInfoPanel.add(new JLabel("当前时间："), gbc);

        gbc.gridx = 1;
        timeInfoPanel.add(currentDateTimeLabel, gbc);

        gbc.gridx = 2;
        timeInfoPanel.add(copyDateTimeButton, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        timeInfoPanel.add(new JLabel("当前时间戳："), gbc);

        gbc.gridx = 1;
        timeInfoPanel.add(currentTimestampLabel, gbc);

        gbc.gridx = 2;
        timeInfoPanel.add(copyTimestampButton, gbc);

        // 添加到主面板顶部
        add(timeInfoPanel, BorderLayout.NORTH);

        // ===== 原有转换区域（略）=====

        // 时间戳转日期部分
        timestampField = new JTextField(30);
        toDatetimeButton = new JButton("→ 转换为日期");
        toDatetimeButton.addActionListener(this::convertTimestampToDateTime);

        // 日期转时间戳部分
        datetimeField = new JTextField(30);
        toTimestampButton = new JButton("→ 转换为时间戳");
        toTimestampButton.addActionListener(this::convertDateTimeToTimestamp);

        // 结果展示区域
        resultLabel = new JLabel(" ");
        resultLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        resultLabel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));

        // 复制按钮
        copyButton = new JButton("复制结果");
        copyButton.setEnabled(false); // 初始不可用
        copyButton.addActionListener(this::copyToClipboard);

        // 布局组合
        JPanel panel = new JPanel(new GridBagLayout());
        gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;

        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(new JLabel("时间戳 (10/13位):"), gbc);

        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        panel.add(timestampField, gbc);

        gbc.gridx = 2;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        panel.add(toDatetimeButton, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(new JLabel("日期格式:"), gbc);

        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        panel.add(datetimeField, gbc);

        gbc.gridx = 2;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        panel.add(toTimestampButton, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        panel.add(resultLabel, gbc);

        gbc.gridx = 2;
        gbc.gridwidth = 1;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        panel.add(copyButton, gbc);

        add(panel, BorderLayout.CENTER);
    }

    // 更新当前时间与时间戳
    private void updateCurrentTime() {
        LocalDateTime now = LocalDateTime.now();
        long timestamp = now.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        currentDateTimeLabel.setText("当前时间：" + now.format(formatter));
        currentTimestampLabel.setText("当前时间戳：" + timestamp);
    }

    // 定时刷新当前时间
    private void startAutoUpdateTime() {
        Timer timer = new Timer(1000, e -> updateCurrentTime());
        timer.setRepeats(true);
        timer.start();
    }

    private void convertTimestampToDateTime(ActionEvent e) {
        String input = timestampField.getText().trim();

        if (input.isEmpty()) {
            resultLabel.setText("请输入有效的时间戳");
            copyButton.setEnabled(false);
            return;
        }

        try {
            long timestamp = Long.parseLong(input);

            LocalDateTime dateTime;
            if (input.length() == 13) {
                dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
            } else if (input.length() == 10) {
                dateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault());
            } else {
                resultLabel.setText("请输入 10 位或 13 位有效时间戳");
                copyButton.setEnabled(false);
                return;
            }

            String formatted = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            lastResult = formatted;
            resultLabel.setText("转换结果: " + formatted);
            copyButton.setEnabled(true);
        } catch (NumberFormatException ex) {
            resultLabel.setText("请输入有效的数字时间戳");
            copyButton.setEnabled(false);
        }
    }

    private void convertDateTimeToTimestamp(ActionEvent e) {
        String input = datetimeField.getText().trim();

        if (input.isEmpty()) {
            resultLabel.setText("请输入有效的日期");
            copyButton.setEnabled(false);
            return;
        }

        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime dateTime = LocalDateTime.parse(input, formatter);
            long timestamp = dateTime.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();

            lastResult = String.valueOf(timestamp);
            resultLabel.setText("转换结果: " + lastResult);
            copyButton.setEnabled(true);
        } catch (Exception ex) {
            resultLabel.setText("日期格式错误，请使用 yyyy-MM-dd HH:mm:ss");
            copyButton.setEnabled(false);
        }
    }

    private void copyToClipboard(ActionEvent e) {
        if (!lastResult.isEmpty()) {
            StringSelection selection = new StringSelection(lastResult);
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(selection, null);
            JOptionPane.showMessageDialog(this, "已复制到剪贴板：" + lastResult);
        }
    }

    private void copyText(String text) {
        if (text != null && !text.isEmpty()) {
            StringSelection selection = new StringSelection(text);
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            clipboard.setContents(selection, null);
            JOptionPane.showMessageDialog(this, "已复制到剪贴板：" + text);
        }
    }
}
